package com.motorola.accessories;

import java.util.ArrayList;

import com.motorola.accessories.provider.ProviderInfo;

import android.app.ProgressDialog;
import android.content.AsyncQueryHandler;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteException;
import android.os.AsyncTask;
import android.os.Bundle;
import android.preference.PreferenceActivity;
import android.preference.PreferenceScreen;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.BaseAdapter;
import android.widget.Button;

public class UpgradeNotificationActivity extends PreferenceActivity implements UpdateAccessoriesInfo{
    private static final String TAG = "MotoAccessoriesActivity";
    private static final int MESSAGE_QUERY_TOKEN = 1;
    private static final int MENU_DELETE = 0;
    private PreferenceScreen mPreferenceScreen = null;
    private boolean mIsDeleteScreen = false;
    private TittlePreference mTittle;
    private TittlePreference mDockTittle;
    private TittlePreference mHeardsetTittle;

    private Button mButton;

    private final ArrayList<AccessoriesEntry> mDockList = new ArrayList<AccessoriesEntry>();
    private final ArrayList<AccessoriesEntry> mHeadsetList = new ArrayList<AccessoriesEntry>();

    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.accessories_list);
        addPreferencesFromResource(R.xml.accessories_screen);
        mTittle = new TittlePreference(this, TittlePreference.HAS_INFO_TYPE);
        mHeardsetTittle = new TittlePreference(this, TittlePreference.HEARDSET_INFO_TYPE);
        mDockTittle = new TittlePreference(this, TittlePreference.DOCK_INFO_TYPE);
        mPreferenceScreen = getPreferenceScreen();
        mButton = (Button) findViewById(R.id.button);
        mButton.setOnClickListener(new OnClickListener(){
            public void onClick(View v) {
                mButton.setEnabled(false);
                mButton.setText(getResources().getString(R.string.checking_now));
                buttonClick();
            }
        });
        Button cancel = (Button) findViewById(R.id.cancel);
        cancel.setOnClickListener(new OnClickListener(){
            public void onClick(View v) {
                ScreenChangeToDeleteScreen(false);
            }
        });
        Button delete = (Button) findViewById(R.id.delete);
        delete.setOnClickListener(new OnClickListener(){
            public void onClick(View v) {
                deleteClick();
            }
        });
        Button button1 = (Button) findViewById(R.id.test);
        button1.setOnClickListener(new OnClickListener(){
            public void onClick(View v) {
                testClick();
            }
        });
        startQuery();
    }

    private void deleteClick(){
        new AsyncTask<Void, Void, Boolean>() {
            ProgressDialog mDialog = new ProgressDialog(UpgradeNotificationActivity.this);
            protected void onPreExecute() {
                mDialog.setMessage(UpgradeNotificationActivity.this.getResources().getString(R.string.wait_delete));
                mDialog.show();
            }
            protected Boolean doInBackground(Void... arg0) {
                boolean delete = false;
                for (int i = 0;i < mDockList.size();i++) {
                    AccessoriesEntry entry = mDockList.get(i);
                    if (entry.isChecked()) {
                        int id = entry.getId();
                        boolean needUpdateNextInfo = entry.getStatus() == AccessoriesEntry.IN_PROGRESS;
                        mDockList.remove(entry);
                        if(needUpdateNextInfo){
                            entry.setDeleted();
                        }
                        i--;
                        getContentResolver().delete(ProviderInfo.ACCESSORIES_CONTENT_URI, "_id=?", new String[]{String.valueOf(id)});
                        delete = true;
                    }
                }
                for (int i = 0;i < mHeadsetList.size();i++) {
                    AccessoriesEntry entry = mHeadsetList.get(i);
                    if (entry.isChecked()) {
                        int id = entry.getId();
                        boolean needUpdateNextInfo = entry.getStatus() == AccessoriesEntry.IN_PROGRESS;
                        mHeadsetList.remove(entry);
                        if(needUpdateNextInfo){
                            entry.setDeleted();
                        }
                        i--;
                        getContentResolver().delete(ProviderInfo.ACCESSORIES_CONTENT_URI, "_id=?", new String[]{String.valueOf(id)});
                        delete = true;
                    }
                }
                return delete;
            }
            protected void onPostExecute(Boolean needUpdateScreen){
                mDialog.dismiss();
                if (needUpdateScreen){
                    updateScreen();
                }
            }
        }.execute();
    }

    private void startQuery(){
        QueryHandler queryHandler = new QueryHandler(this, this);
        try {
            queryHandler.startQuery(0, MESSAGE_QUERY_TOKEN, ProviderInfo.ACCESSORIES_CONTENT_URI, null, null, null, null);
        } catch (SQLiteException e) {
        }
    }

    public void onResume(){
        super.onResume();
    }

    private void buttonClick(){
        if (mDockList != null && mDockList.size() > 0) {
            for (int i=0;i<mDockList.size();i++) {
                mDockList.get(i).setStatus(AccessoriesEntry.NO_STATUS);
            }
        }
        if (mHeadsetList != null && mHeadsetList.size() > 0) {
            for (int i=0;i<mHeadsetList.size();i++) {
                mHeadsetList.get(i).setStatus(AccessoriesEntry.NO_STATUS);
            }
        }
        refresh();
        updateNextInfo();
    }

    public void updateNextInfo() {
        if (mDockList != null && mDockList.size() > 0) {
            for (int i=0;i<mDockList.size();i++) {
                AccessoriesEntry entry = mDockList.get(i);
                if(entry.getStatus() != AccessoriesEntry.DONE) {
                    if (entry.getStatus() == AccessoriesEntry.NO_STATUS) {
                        entry.setStatus(AccessoriesEntry.IN_PROGRESS);
                        entry.requestInfo();
                        if (!mIsDeleteScreen) {
                            refresh();
                        }
                        return;
                    }
                } else if (entry.getStatus() == AccessoriesEntry.IN_PROGRESS) {
                    return;
                } else {

                }
            }
        }
        if (mHeadsetList != null && mHeadsetList.size() > 0) {
            for (int i=0;i<mHeadsetList.size();i++) {
                AccessoriesEntry entry = mHeadsetList.get(i);
                if(entry.getStatus() != AccessoriesEntry.DONE) {
                    if (entry.getStatus() == AccessoriesEntry.NO_STATUS) {
                        entry.setStatus(AccessoriesEntry.IN_PROGRESS);
                        entry.requestInfo();
                        if (!mIsDeleteScreen) {
                            refresh();
                        }
                    }
                    return;
                } else if (entry.getStatus() == AccessoriesEntry.IN_PROGRESS) {
                    return;
                } else {

                }
            }
        }
        if (!mIsDeleteScreen) {
            refresh();
        }
        mButton.setEnabled(true);
        mButton.setText(getResources().getString(R.string.check_again));
    }

    private void testClick(){
        ContentValues values = new ContentValues();
        values.put(ProviderInfo.TableColumns.ACCESSORY_CATEGORY, 1);
        values.put(ProviderInfo.TableColumns.SW_VERSION, "2.8");
        getContentResolver().insert(ProviderInfo.ACCESSORIES_CONTENT_URI, values);
        values.clear();
        values.put(ProviderInfo.TableColumns.ACCESSORY_CATEGORY, 0);
        values.put(ProviderInfo.TableColumns.SW_VERSION, "3.0");
        getContentResolver().insert(ProviderInfo.ACCESSORIES_CONTENT_URI, values);
    }

    private class QueryHandler extends AsyncQueryHandler {
        private Context mContext = null;
        UpdateAccessoriesInfo mUpdate;

        public QueryHandler(Context context, UpdateAccessoriesInfo update) {
            super(context.getContentResolver());
            mContext = context;
            mUpdate = update;
        }

        protected void onQueryComplete(int token, Object cookie, Cursor cursor) {
            mDockList.clear();
            mHeadsetList.clear();
            if (cursor != null && cursor.moveToFirst() && cursor.getCount() != 0) {
                switch ((Integer) cookie) {
                    case MESSAGE_QUERY_TOKEN:
                        do {
                            int id = cursor.getInt(cursor.getColumnIndex(ProviderInfo.TableColumns.ID));
                            int category = cursor.getInt(cursor.getColumnIndex(ProviderInfo.TableColumns.ACCESSORY_CATEGORY));
                            switch (category) {
                            case 0:
                                mDockList.add(new AccessoriesEntry(mContext, mUpdate, id));
                                break;
                            case 1:
                                mHeadsetList.add(new AccessoriesEntry(mContext, mUpdate, id));
                                break;
                            default:
                                break;

                            }
                        } while (cursor.moveToNext());
                        break;
                    default:
                        Log.e(TAG, "Bad query token: " + token);
                        break;
                }

                cursor.close();
            }
            updateScreen();
            invalidateOptionsMenu();
            if (cursor != null) {
                cursor.close();
            }
        }
    }

    private void updateScreen() {
        mPreferenceScreen.removeAll();
        if (mDockList.size() + mHeadsetList.size() > 0) {
            mPreferenceScreen.addPreference(mTittle);
            if (mDockList.size() > 0) {
                mPreferenceScreen.addPreference(mDockTittle);
                for (int i = 0;i < mDockList.size();i++) {
                    mPreferenceScreen.addPreference(mDockList.get(i));
                }
            }
            if (mHeadsetList.size() > 0) {
                mPreferenceScreen.addPreference(mHeardsetTittle);
                for (int i = 0;i < mHeadsetList.size();i++) {
                    mPreferenceScreen.addPreference(mHeadsetList.get(i));
                }
            }
        } else {
            mPreferenceScreen.addPreference(new TittlePreference(this, TittlePreference.NO_INFO_TYPE));
            if(mIsDeleteScreen) {
                ScreenChangeToDeleteScreen(false);
            }
            Log.e(TAG, "Cannot init the cursor for the thread list.");
        }
    }

    public boolean onCreateOptionsMenu(Menu menu) {
        if (!mIsDeleteScreen) {
            if (mDockList.size() + mHeadsetList.size() > 0) {
                menu.add(0, MENU_DELETE, 0, R.string.delete_accessories);
            }
        }
        return super.onCreateOptionsMenu(menu);
    }

    public boolean onOptionsItemSelected(MenuItem item) {
        final int itemId = item.getItemId();
        if (itemId == MENU_DELETE) {
            ScreenChangeToDeleteScreen(true);
            return true;
        } else {
            return super.onOptionsItemSelected(item);
        }
    }

    private void ScreenChangeToDeleteScreen(boolean toDeleteScreen) {
        mIsDeleteScreen = toDeleteScreen;
        invalidateOptionsMenu();
        if (mDockList != null && mDockList.size() > 0) {
            for (int i = 0; i < mDockList.size(); i++) {
                mDockList.get(i).setDeleteScreen(toDeleteScreen);
            }
        }
        if (mHeadsetList != null && mHeadsetList.size() > 0) {
            for (int i = 0; i < mHeadsetList.size(); i++) {
                mHeadsetList.get(i).setDeleteScreen(toDeleteScreen);
            }
        }
        refresh();
        if (toDeleteScreen) {
            findViewById(R.id.button).setVisibility(View.GONE);
            findViewById(R.id.test).setVisibility(View.GONE);
            findViewById(R.id.cancel).setVisibility(View.VISIBLE);
            findViewById(R.id.delete).setVisibility(View.VISIBLE);
        } else {
            findViewById(R.id.delete).setVisibility(View.GONE);
            findViewById(R.id.cancel).setVisibility(View.GONE);
            findViewById(R.id.test).setVisibility(View.VISIBLE);
            findViewById(R.id.button).setVisibility(View.VISIBLE);
        }
    }

    private void refresh() {
        BaseAdapter screenListAdapter = (BaseAdapter)mPreferenceScreen.getRootAdapter();
        screenListAdapter.notifyDataSetChanged();
    }

    public void onBackPressed() {
        if (mIsDeleteScreen) {
            ScreenChangeToDeleteScreen(false);
        } else {
            super.onBackPressed();
        }
    }

}